package com.sky.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.context.BaseContext;
import com.sky.dto.SetmealDTO;
import com.sky.dto.SetmealPageQueryDTO;
import com.sky.entity.Setmeal;
import com.sky.entity.SetmealDish;
import com.sky.exception.BaseException;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.SetmealService;
import com.sky.vo.DishItemVO;
import com.sky.vo.SetmealVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.sky.constant.RedisConstant.SETMEAL_KRY;

@Service
@Slf4j
@RequiredArgsConstructor
public class SetmealServiceImpl implements SetmealService {

    private final SetmealMapper setmealMapper;
    private final SetmealDishMapper setmealDishMapper;
    private final DishMapper dishMapper;
    private final StringRedisTemplate redisTemplate;

    /**
     * 分页查询套餐信息
     *
     * @param pageQueryDTO
     * @return
     */
    @Override
    public PageResult pageSetmeal(SetmealPageQueryDTO pageQueryDTO) {
        //开启分页查询
        PageHelper.startPage(pageQueryDTO.getPage(), pageQueryDTO.getPageSize());
        //进行分页查询
        Page<SetmealVO> page = setmealMapper.getListSetmeal(pageQueryDTO);
        //返回分页对象
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 保存套餐信息
     *
     * @param setmealDTO
     */
    @Override
    @Transactional
    public void save(SetmealDTO setmealDTO) {
        log.info("套餐信息:{}", setmealDTO);
        //获取套餐下的菜品
        List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes();
        //套餐信息拷贝
        Setmeal setmeal = BeanUtil.copyProperties(setmealDTO, Setmeal.class);
        //添加属性
        setmeal.setCreateTime(LocalDateTime.now());
        setmeal.setUpdateTime(LocalDateTime.now());
        setmeal.setCreateUser(BaseContext.getCurrentId());
        setmeal.setUpdateUser(BaseContext.getCurrentId());
        //判断分类下的套餐名是否重复
        Long categoryId = setmeal.getCategoryId();
        long count = setmealMapper.countByCategoryIdAndName(categoryId, setmeal.getName());
        if (count != 0) {
            throw new BaseException("此分类下的已有此套餐");
        }
        //删除套餐缓存
        redisTemplate.delete(SETMEAL_KRY + setmealDTO.getId());
        log.info("套餐缓存已经删除");
        //保存套餐信息
        setmealMapper.saveSetmeal(setmeal);
        if (setmealDishes != null && !setmealDishes.isEmpty()) {
            //获取套餐id
            Long setmealId = setmeal.getId();
            //保存套餐下的菜品
            setmealDishes.forEach(item -> item.setSetmealId(setmealId));
            setmealDishMapper.saveSetmealDish(setmealDishes);
        }

    }

    /**
     * 套餐的启用和停用
     *
     * @param status
     * @param id
     */
    @Override
    public void startOrStop(Integer status, Long id) {
        //获取关联的菜品
        List<Long> longList = setmealDishMapper.selectSetmealDish(id).stream().map(SetmealDish::getDishId).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(longList)) {
            //判断套餐下的菜品是否起售
            long count = dishMapper.countStatusByIds(longList);
            if (count != 0) {
                throw new BaseException("套餐下的菜品起售中,不可停用");
            }
        }
        //删除缓存
        redisTemplate.delete(SETMEAL_KRY + id);
        log.info("套餐缓存已经删除");
        setmealMapper.startOrStop(status, id);
    }

    /**
     * 根据id删除套餐信息
     *
     * @param ids
     */
    @Override
    @Transactional
    public void deleteByIds(List<Long> ids) {
        if (CollUtil.isEmpty(ids)) {
            throw new BaseException("请选择删除的套餐");
        }
        //获取删除的套餐信息
        long count = setmealMapper.getCountListSetmeal(ids);
        if (count != 0) {
            throw new BaseException("套餐起售中,不可删除");
        }
        //删除缓存
        ArrayList<String> stringList = new ArrayList<>();
        ids.forEach(item -> {
            stringList.add(SETMEAL_KRY + item);
        });
        redisTemplate.delete(stringList);
        //删除套餐
        setmealMapper.deleteByIds(ids);
        //删除套餐下的商品
        setmealDishMapper.deleteByIds(ids);
    }

    /**
     * 根据id查询套餐信息
     *
     * @param id
     * @return
     */
    @Override
    public SetmealDTO getById(Long id) {
        SetmealDTO setmeal = setmealMapper.getById(id);
        //获取套餐下的菜品
        List<SetmealDish> list = setmealDishMapper.selectSetmealDish(id);
        if (CollUtil.isNotEmpty(list)) {
            setmeal.setSetmealDishes(list);
        } else {
            setmeal.setSetmealDishes(new ArrayList<>());
        }
        return setmeal;
    }

    /**
     * 更新套餐信息
     *
     * @param setmealDTO
     */
    @Override
    @Transactional
    public void update(SetmealDTO setmealDTO) {
        //对象拷贝
        Setmeal setmeal = BeanUtil.copyProperties(setmealDTO, Setmeal.class);
        //属性赋值
        setmeal.setUpdateTime(LocalDateTime.now());
        setmeal.setUpdateUser(BaseContext.getCurrentId());
        //判断分类下的套餐名是否重复
        if (setmealMapper.getById(setmeal.getId()).getName().equals(setmeal.getName())) {
            //更新套餐信息
            setmealMapper.updateSetmeal(setmeal);
        } else {
            //判断分类下的套餐名是否重复
            Long categoryId = setmeal.getCategoryId();
            long count = setmealMapper.countByCategoryIdAndName(categoryId, setmeal.getName());
            if (count != 0) {
                throw new BaseException("此分类下的已有此套餐");
            } else {
                //删除缓存
                redisTemplate.delete(SETMEAL_KRY + setmealDTO.getId());
                //更新套餐信息
                setmealMapper.updateSetmeal(setmeal);
            }
        }


        //获取套餐下的菜品
        List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes();
        if (setmealDishes != null && !setmealDishes.isEmpty()) {
            //删除套餐下的菜品
            setmealDishMapper.deleteBySetmealId(setmeal.getId());
            //保存套餐下的菜品
            setmealDishes.forEach(item -> item.setSetmealId(setmeal.getId()));
            setmealDishMapper.saveSetmealDish(setmealDishes);
        }
    }

    /**
     * 获取分类下的所有套餐
     *
     * @param categoryId
     * @return
     */
    @Override
    public List<Setmeal> list(Long categoryId) {
        String key = SETMEAL_KRY + categoryId;
        //查询缓存
        ListOperations<String, String> redisList = redisTemplate.opsForList();
        List<String> setmealList = redisList.range(key, 0, -1);
        if (CollUtil.isNotEmpty(setmealList)) {
            ArrayList<Setmeal> setmeals = new ArrayList<>();
            for (String s : setmealList) {
                Setmeal setmeal = JSONObject.parseObject(s, Setmeal.class);
                setmeals.add(setmeal);
            }
            //返回数据
            return setmeals;
        }
        //查询数据库
        List<Setmeal> list = setmealMapper.list(categoryId);
        ArrayList<String> redisCacheList = new ArrayList<>();
        for (Setmeal setmeal : list) {
            redisCacheList.add(JSONObject.toJSONString(setmeal));
        }
        //写入缓存
        redisList.leftPushAll(key, redisCacheList);
        //返回数据
        return list;
    }

    /**
     * 根据套餐id查询包含的菜品列表
     *
     * @param id
     * @return
     */
    @Override
    public List<DishItemVO> dishList(Long id) {
        return setmealDishMapper.getAllDishById(id);
    }
}
